package service

import (
	"errors"
	"fmt"
	"math"
	"math/rand"
	"strings"
	"time"

	"github.com/google/uuid"
	"github.com/smash-llj/Nexa-server/models"
	"github.com/smash-llj/Nexa-server/models/request"
	"github.com/smash-llj/Nexa-server/models/response"
	"gorm.io/gorm"
)

var groupService *GroupService

type GroupService struct {
	BaseService
}

func NewGroupService() *GroupService {
	if groupService == nil {
		return &GroupService{
			NewBaseService(),
		}
	}
	return groupService
}
func GenerateNumericId() int {
	rand.Seed(time.Now().UnixNano()) // 使用当前时间戳设置种子
	m := 10000000
	i := 99999999
	return rand.Intn(i-m) + m
}

// CreateGroup 创建群组并自动将群主加入成员表，角色为群主
func (g *GroupService) CreateGroup(uId uint, memberIds []int) (*models.Group, error) {
	//先创建群聊 然后创建群聊session
	group := models.Group{
		SessionId: uuid.New().String(),
		NumberId:  GenerateNumericId(),
		OwnerId:   int(uId),
		Name:      "未命名群聊",
	}
	if err := g.Gorm.Model(&models.Group{}).Create(&group).Error; err != nil {
		return nil, err
	}
	groupMembers := make([]models.GroupMember, 0, len(memberIds)+1)
	groupMembers = append(groupMembers, models.GroupMember{
		GroupId: group.Id,
		UserId:  uId,
		Role:    1,
	})

	for _, userId := range memberIds {
		groupMembers = append(groupMembers, models.GroupMember{
			GroupId: group.Id,
			UserId:  uint(userId),
			Role:    0,
		})
	}
	err := g.Gorm.Model(&models.GroupMember{}).Create(&groupMembers).Error
	if err != nil {
		return nil, err
	}

	return &group, nil

}

func (g *GroupService) GetGroupMessage(req request.GetGroupMessageReq, userId uint) (*response.MessageResp, error) {
	var totalMessages int64
	sessionID := strings.TrimSpace(req.SessionId)
	if sessionID == "" {
		return nil, nil
	}
	if err := g.Gorm.Model(&models.Message{}).
		Where("session_id = ?", sessionID).
		Count(&totalMessages).Error; err != nil {
		return nil, err
	}
	if totalMessages == 0 {
		return nil, nil
	}

	// 查询消息（分页 + 预加载 Sender）
	var messages []response.MessageListResp
	if err := g.Gorm.Table("message").
		Select("message.*, user.username AS name, user.avatar").
		Joins("JOIN user ON user.id = message.send_id").
		Where("message.session_id = ?", sessionID).
		Scopes(req.PageInfo.Paginate()).
		Order("message.created_at DESC").
		Find(&messages).Error; err != nil {
		return nil, err
	}

	// 更新未读为 0（忽略错误）
	_ = g.Gorm.Model(&models.Session{}).
		Where("session_id = ? AND user_id = ? AND to_id = ?", sessionID, userId, req.GroupId).
		Update("unread", 0).Error

	return &response.MessageResp{
		Messages:   messages,
		Total:      totalMessages,
		TotalPages: int(math.Ceil(float64(totalMessages) / float64(req.PageInfo.PageSize))),
	}, nil
}

func (g *GroupService) DetailGroup(groupId uint) (*models.Group, []models.User, error) {
	var group models.Group
	var groupMembers []models.User
	if err := g.Gorm.Where("id=?", groupId).Find(&group).Error; err != nil {
		return nil, nil, err
	}
	if err := g.Gorm.Where("id IN (?)", g.Gorm.Model(&models.GroupMember{}).
		Select("user_id").
		Where("group_id = ?", groupId)).Find(&groupMembers).Error; err != nil {
		return nil, nil, err
	}

	return &group, groupMembers, nil
}

// GetUserGroups 查询已经加入的群聊
func (g *GroupService) GetUserGroups(userId uint) ([]response.GetUserGroupsResp, error) {
	var groups []response.GetUserGroupsResp
	err := g.Gorm.
		Table("group_member").
		Select("`group`.`name`, `group`.`avatar`, `group`.`session_id`, `group`.`number_id`, `group`.`id`").
		Joins("JOIN `group` ON `group`.`id` = `group_member`.`group_id`").
		Where("group_member.user_id = ?", userId).
		Scan(&groups).Error
	if err != nil {
		return nil, fmt.Errorf("failed to get user groups: %w", err)
	}
	return groups, nil
}

func (g *GroupService) GetGroupMemberList(groupId uint) (*response.GetGroupMemberAndOwnersResp, error) {
	var groupMembers []response.GetGroupMembersResp
	var OwnerId int
	if err := g.Gorm.Model(&models.Group{}).Select("owner_id").Where("id = ?", groupId).Find(&OwnerId).Error; err != nil {
		return nil, err
	}
	if err := g.Gorm.
		Table("group_member").
		Select("user.id,user.username, user.avatar, user.uuid,user.sign,user.address,user.birthdate,user.gender,user.bg_image,group_member.role AS role").
		Joins("JOIN `user` ON user.id = group_member.user_id").
		Where("group_member.group_id = ?", groupId).
		Order("group_member.role DESC").
		Find(&groupMembers).Error; err != nil {
		return nil, fmt.Errorf("failed to get group members: %w", err)
	}
	return &response.GetGroupMemberAndOwnersResp{
		OwnerId: OwnerId,
		Members: groupMembers,
	}, nil
}

func (g *GroupService) JoinGroup(groupReq request.JoinGroupParamsReq) error {
	var group models.Group
	err := g.Gorm.First(&group, groupReq.GroupId).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("群不存在")
	} else if err != nil {
		return fmt.Errorf("database error checking group existence: %w", err)
	}

	groupMember := models.GroupMember{
		GroupId: uint(groupReq.GroupId),
		UserId:  uint(groupReq.UserId),
	}

	tx := g.Gorm.Begin()
	err = tx.Create(&groupMember).Error
	if err != nil {
		tx.Rollback()
		return fmt.Errorf("database error creating group membership: %w", err)
	}
	tx.Commit()
	return nil
}

func (g *GroupService) UpdateGroupInfo(groupReq request.UpdateGroupInfoReq) error {
	return g.Gorm.Model(&models.Group{}).Where("id=?", groupReq.GroupId).Updates(groupReq).Error
}
